var express = require('express')
var router = express.Router()
const path = require('path')

const fs = require('fs')
const util = require('util')
const { chapter } = require('../modules/chapter')
const { content } = require('../modules/content')

const fileExists = util.promisify(fs.exists)
const fileWrite = util.promisify(fs.writeFile)
const mkdir = util.promisify(fs.mkdir)
const readFile = util.promisify(fs.readFile)

var crypto = require('crypto')
function md5 (text) {
  return crypto.createHash('md5').update(text).digest('hex')
};

/* GET users listing. */
router.get('/:id', async function (req, res, next) {
  const book = path.join(__dirname, '..', '/temp/' + req.params.id + '/book.json')
  const exists = await fileExists(book)
  if (exists) {
    let chapterList = await getChapterList(req.params.id)
    chapterList = chapterList.map((item, i) => {
      return {
        chapterName: item.chapterName,
        chapterUrl: `/book/${req.params.id}/chapter/${i}`
      }
    })
    res.render('book', {
      ...require(book),
      chapterList
    })
  } else {
    res.render('404', { message: 'book not found' })
  }
})

router.get('/:id/chapter', async function (req, res, next) {
  const bookJson = path.join(__dirname, '..', '/temp/' + req.params.id + '/book.json')
  const chapterJson = path.join(__dirname, '..', '/temp/' + req.params.id + '/chapter.json')
  const exists2 = await fileExists(chapter)
  if (exists2) {
    res.json(require(chapter))
  } else {
    const source = require('../sources/a.json')
    const bookObj = require(bookJson)
    const chapterObj = await chapter(source, bookObj.chapterUrl)
    await fileWrite(chapterJson, JSON.stringify(chapterObj))
    res.json(chapterObj)
  }
})

async function getChapterList (id) {
  const bookJson = path.join(__dirname, '..', '/temp/' + id + '/book.json')
  const chapterJson = path.join(__dirname, '..', '/temp/' + id + '/chapter.json')
  const exists2 = await fileExists(chapter)
  if (exists2) {
    return require(chapter)
  } else {
    const source = require('../sources/a.json')
    const bookObj = require(bookJson)
    const chapterObj = await chapter(source, bookObj.chapterUrl)
    await fileWrite(chapterJson, JSON.stringify(chapterObj))
    return chapterObj
  }
}

router.get('/:id/chapter/:chapterId', async function (req, res, next) {
  const chapterJson = path.join(__dirname, '..', '/temp/' + req.params.id + '/chapter.json')
  const chapterList = require(chapterJson)

  if (chapterList[req.params.chapterId]) {
    const source = require('../sources/a.json')
    const contentUrl = chapterList[req.params.chapterId].contentUrl
    const contentFolderPath = path.join(__dirname, '..', '/temp/' + req.params.id + '/chapter/')
    const contentPath = path.join(contentFolderPath, md5(contentUrl) + '.html')
    const exists = await fileExists(contentPath)
    let data = {
      title: chapterList[req.params.chapterId].chapterName,
      prevPageUrl: req.params.chapterId > 0 ? `/book/${req.params.id}/chapter/${+req.params.chapterId - 1}` : '#title',
      nextPageUrl: req.params.chapterId < chapterList.length ? `/book/${req.params.id}/chapter/${+req.params.chapterId + 1}` : '#title',
      bookUrl: `/book/${req.params.id}`,
      theme: 'theme-6'
    }
    if (exists) {
      const content = await readFile(contentPath)
      data = {
        content,
        ...data
      }
    } else {
      const contentObj = await content(source, contentUrl)
      if (!await fileExists(contentFolderPath)) await mkdir(contentFolderPath)
      await fileWrite(contentPath, contentObj.content)
      data = {
        ...contentObj,
        ...data
      }
    }
    res.render('content', data)
  } else {
    res.render('404', { message: 'chapter not found' })
  }
})

module.exports = router
